package club.jdiy.dev.zlt.controller;

import club.jdiy.admin.interceptor.GuestDisabled;
import club.jdiy.core.JDiyContext;
import club.jdiy.core.base.domain.Pager;
import club.jdiy.core.base.domain.Ret;
import club.jdiy.core.sql.EntityFieldInfo;
import club.jdiy.dev.controller.JDiyController;
import club.jdiy.dev.entity.JDiyUi;
import club.jdiy.dev.types.UiTpl;
import club.jdiy.core.ex.JDiyException;
import club.jdiy.dev.zlt.service.JDevMenuService;
import club.jdiy.dev.zlt.service.JDevPageService;
import club.jdiy.utils.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
@RequestMapping("mgmt/JDiyAdmin")
public class JDevPageCtrl extends JDevCtrl<JDiyUi, JDevPageService> implements JDiyController {

    @RequestMapping("ui.form")
    public String form(String id, Integer clone, ModelMap map) {
        if (StringUtils.isEmpty(id) || "0".equals(id)) {
            map.put("vo", new JDiyUi("0"));
        } else {
            map.put("vo", service.findById(id).orElse(null));
        }
        map.put("tables", listTables());
        map.put("entities", jDiyContext.getDao().getEntityMeta());
        map.put("uiTpl", UiTpl.values());
        map.put("clone", clone);
        return "ui.add";
    }


    @RequestMapping(value = "ui.list")
    public String list(JDiyUi qo, String orderField, String orderDirection,
                       @RequestParam(defaultValue = "15") Integer pageSize,
                       @RequestParam(defaultValue = "1") Integer page, ModelMap map) {
        map.put("tableList", listTables());
        Pager<JDiyUi> pager = service.findPager(pageSize, page, qo, orderField, orderDirection);
        map.put("qo", qo);
        map.put("pager", pager);
        map.put("orderField", orderField);
        map.put("orderDirection", orderDirection);
        map.put("uiTplList", UiTpl.values());
        map.put("uiTplMap", Arrays.stream(UiTpl.values()).collect(Collectors.toMap(Enum::name, t -> t, (a, b) -> b)));
        return "ui.lst";
    }

    @GuestDisabled
    @RequestMapping("ui.clone")
    @ResponseBody
    public Ret<?> clone(JDiyUi vo) {
        try {
            vo = service.clone(vo);
            Map<String, String> map = new HashMap<>();
            map.put("url", "/mgmt/JDiyAdmin/" + vo.getType() + ".design." + vo.getId());
            map.put("tit", vo.getName());
            return Ret.success(map);
        } catch (Exception ex) {
            return Ret.error(ex);
        }
    }


    @RequestMapping("ui.url")
    public String createUrl(ModelMap map, String id) {
        JDiyUi ui = service.findById(id).orElse(null);
        if (ui == null) return Ret.direct(context.getResponse(), Ret.Type.msg, "目标界面不存在或被删除！");
        map.put("vo", ui);
        if (ui.getType()!=UiTpl.form) {
            map.put("menus", menuService.findRootList());
        }
        return "ui.url";
    }

    @GuestDisabled
    @RequestMapping("ui.delete.{id}")
    @ResponseBody
    public Ret<String> delete(@PathVariable String id) {
        try {
            service.findById(id).ifPresent(service::delete);
            return Ret.success();
        } catch (JDiyException le) {
            return Ret.error(le);
        } catch (Exception le) {
            le.printStackTrace();
            return Ret.fail(Ret.RetCode.fail.getCode(), "对不起，删除失败，可能此条目已被系统业务使用。");
        }
    }


    @GuestDisabled
    @ResponseBody
    @RequestMapping("ui.updateName")
    public Ret<?> updateName(JDiyUi vo) {
        try {
            service.updateName(vo);
            return Ret.success();
        } catch (Exception je) {
            return Ret.error(je);
        }
    }

    @RequestMapping("ui.icon")
    public String chooseIcon(ModelMap map, String fn, String value) {
        map.put("fn", fn);
        map.put("value", value);
        return "ui.icon";
    }


    @RequestMapping("ui.meta")
    @ResponseBody
    public Ret<?> meta(String pageId) {
        try {
            JDiyUi po = service.findById(pageId).orElseThrow(() -> new JDiyException("获取界面信息失败，不存在或被删除。"));
            return StringUtils.hasText(po.getMetaData()) ? Ret.successJson(po.getMetaData()) : Ret.successJson("{}");
        } catch (Exception ex) {
            return Ret.error(ex);
        }
    }


    @RequestMapping("ui.columns")
    @ResponseBody
    public Ret<?> columns(String table) {
        try {
            context.getCacheClient().delete("JDiyTableColumnsMetaInfo_"+table);
            return Ret.success(jDiyContext.getDao().getTableInfo(table).getColumns().values()
                    .stream().map(it -> new String[]{it.getName(), it.getType()})
                    .collect(Collectors.toList()));
        } catch (Exception e) {
            return Ret.error(e);
        }
    }

    @RequestMapping("ui.fields")
    @ResponseBody
    public Ret<?> fields(String entity) {
        try {
            return Ret.success(jDiyContext.getDao().getEntityMeta(entity).getFieldList()
                    .stream().filter(it -> it.getType() != EntityFieldInfo.Type.LIST)
                    .map(it -> it.getType() == EntityFieldInfo.Type.JOIN
                            ? new String[]{it.getName() + ".id", it.getMemberIdClass().getSimpleName()}
                            : new String[]{it.getName(), it.getTypeClass().getSimpleName()}
                    ).collect(Collectors.toList()));
        } catch (Exception e) {
            return Ret.error(e);
        }
    }

    @Resource
    private JDiyContext jDiyContext;
    @Resource
    private JDevMenuService menuService;
}
